"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs = require("fs");
var path = require("path");
var unit_1 = require("../unit");
/**
 * 该类自身主要负责目录方面的创建与删除
 * */
var FileStrategy = /** @class */ (function () {
    function FileStrategy() {
    }
    /*未测试*/
    FileStrategy.rmDirectorySync = function (_path, index) {
        if (_path) {
            FileStrategy.rmDirectorySync(_path, ++index);
        }
    };
    /*未测试*/
    FileStrategy.rmdir = function (_path) {
        var index = 1;
        _path = unit_1.pathResolve(_path);
        _path = unit_1.markPathSplit(_path);
        for (var i = 1, length_1 = _path.length; i < length_1; i++) {
            _path[i] = _path[(i - 1)] + path.sep + _path[i];
        }
        FileStrategy.rmDirectorySync(_path, index);
    };
    /**
     * path: 创建的文件夹路径
     * 使用相对路径'./'
     * @return {string[]}
     * */
    FileStrategy.createDirectory = function (_path) {
        return __awaiter(this, void 0, void 0, function () {
            var index;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        index = 1;
                        return [4 /*yield*/, FileStrategy.markDirectorySync(unit_1.pathSplit(_path), index)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    FileStrategy.markDirectorySync = function (path, index) {
        if (path.length <= index) {
            return path;
        }
        if (!unit_1.isExist(path[index]))
            fs.mkdirSync(path[index]);
        return FileStrategy.markDirectorySync(path, ++index);
    };
    FileStrategy.writeFile = function (filePath, fileName, data, callback) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, FileStrategy.createDirectory(filePath)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, FileStrategy.write(FileStrategy.pathSplice(filePath, fileName), data, callback)];
                }
            });
        });
    };
    /**
     * 将文件路径与文件名合并成一条路径
     * 使用相对路径'./'
     * */
    FileStrategy.pathSplice = function (filePath, fileName) {
        var _filePath = path.resolve(filePath);
        return _filePath + path.sep + fileName;
    };
    /**
     * 支持相对路径
     * @param filePath {string} 使用相对路径'./'
     * Function: 测试目录是否存在
     * fail: false
     * done: true
     * */
    FileStrategy.isDirectory = function (filePath) {
        var result = unit_1.pathSplit(filePath);
        var r = true;
        result.forEach(function (val) {
            if (!unit_1.isExist(val)) {
                r = false;
            }
        });
        return r;
    };
    FileStrategy.stringToUnit8Array = function (text) {
        // let _textArray = text.split('');
        // utf8中文字符占用3字节
        // const BYTE_LENGTH = 3;
        // let buf = Buffer.alloc(_textArray.length * BYTE_LENGTH);
        var buf = Buffer.from(text);
        buf.write(text);
        return buf;
    };
    /**
     * @param resolve
     * @param reject
     * @param _data 编码后的数据
     * */
    FileStrategy.writeDefaultCallback = function (resolve, reject, _data) {
        return function cb(err) {
            if (err) {
                reject(err);
            }
            resolve(_data);
        };
    };
    /**
     * @param fileName {string} 文件路径与文件名:./test1/a.txt
     * @param data 要写入到文件中的数据
     * @param callback
     * */
    FileStrategy.write = function (fileName, data, callback) {
        if (callback === void 0) { callback = FileStrategy.writeDefaultCallback; }
        var _fileName = path.resolve(fileName);
        var _data;
        if (!Buffer.isBuffer(data)) {
            _data = this.stringToUnit8Array(data);
        }
        return new Promise(function (resolve, reject) {
            return fs.writeFile(_fileName, _data, callback.call(null, resolve, reject, _data));
        });
    };
    /**
     * 可以重命名文件夹名与文件名
     * */
    FileStrategy.rename = function (oldPath, newPath) {
        var _oldPath = path.resolve(oldPath);
        var _newPath = path.resolve(newPath);
        return new Promise(function (resolve, reject) {
            fs.renameSync(_oldPath, _newPath);
            resolve(_newPath);
        });
    };
    FileStrategy.readFile = function (filePath, fileName, isString) {
        if (isString === void 0) { isString = false; }
        return __awaiter(this, void 0, void 0, function () {
            var _filePath;
            return __generator(this, function (_a) {
                if (!FileStrategy.isDirectory(filePath)) {
                    throw '没有找到文件夹';
                }
                _filePath = FileStrategy.pathSplice(path.resolve(filePath), fileName);
                return [2 /*return*/, FileStrategy.read(_filePath, isString)];
            });
        });
    };
    /**
     * @param filePath 文件路径
     * @param isString false返回buffer,true返回字符串
     * 根据fs.lstatSync返回的参数判断该返回成功还是失败的函数
     * */
    FileStrategy.read = function (filePath, isString) {
        function ok(resolve, reject) {
            fs.readFile(filePath, function (err, data) {
                if (err) {
                    reject(err);
                }
                if (isString) {
                    resolve(data);
                }
                else {
                    resolve(data.toString());
                }
            });
        }
        function failure() {
            return new Promise(function (resolve, reject) {
                reject('read is error.');
            });
        }
        return new Promise(function (resolve, reject) {
            if (fs.lstatSync(filePath)) {
                return ok(resolve, reject);
            }
            else {
                return failure();
            }
        });
    };
    return FileStrategy;
}());
exports.default = FileStrategy;
